import ColumnType from '@/framework/constant/ColumnType'
import TypeDiagnose from '@/framework/infra/type/TypeDiagnose'
import ObjectUtil from '@/framework/infra/object/ObjectUtil'
import CollectionUtil from '@/framework/infra/collection/CollectionUtil'

export default class ColumnUtil {
  // 是分组的columns
  static isGroupColumns(columns) {
    if (CollectionUtil.isNotEmpty(columns)) {
      return 'columns' in columns[0]
    }
    return false
  }

  static async findOptionItem(column, value) {
    if (!column.options) {
      return null
    }
    let options = column.options
    if (TypeDiagnose.isEnum(options)) {
      if (Array.isArray(value)) {
        return {
          label: value.map(v => options.getById(v)).join(',')
        }
      }
      return options.getById(value)
    }
    if (options instanceof Promise) {
      // eslint-disable-next-line require-atomic-updates
      options = await options
    }
    return options.find(el => el.value === value)
  }

  static parseColumns(columns) {
    if (!columns) {
      return []
    }
    if (!this.isGroupColumns(columns)) {
      return columns
    }
    const results = columns.reduce((r, a) => {
      r = r.concat(a.columns)
      return r
    }, [])
    return results
  }

  static async parseOptionToMap(column) {
    let result = null
    if (column.type === ColumnType.SELECT || column.type === ColumnType.RADIO) {
      const options = column.options
      if (TypeDiagnose.isEnum(options)) { // 枚举类型
        result = options.getOptions()
      } else if (options instanceof Promise) {
        result = await options
      } else {
        result = options
      }
    }
    if (!result) {
      return null
    }
    return ObjectUtil.parseListToMapObj(result)
  }

  static async getText(column, value) {
    if (!column.displayProp) {
      const item = await this.findOptionItem(column, value)
      if (item) {
        return item.label
      } else if (column.options) {
        return ''
      }
    }
    if (column.type === ColumnType.DATE && value) {
      return value.split(' ')[0]
    }
    // if (column.lang) {
    //   return value[LangTypeEnum.CNT.id]
    // }
    return value
  }
}
